package cn.sell.mbg;

import lombok.extern.log4j.Log4j2;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.Properties;

/**
 * 自定义注释生成器
 * Created by macro on 2018/4/26.
 */
@Log4j2
public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;
    private static final String EXAMPLE_SUFFIX = "Example";
    private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME = "io.swagger.annotations.ApiModelProperty";
    private static final String API_MODEL_PROPERTY_GENERATEDVALUE = "javax.persistence.GeneratedValue";
    private static final String API_MODEL_PROPERTY_ID = "javax.persistence.Id";

    /**
     * 设置用户配置的参数
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
    }

    /**
     * 给字段添加注释
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();

        addFieldJavaDoc(field, remarks);

//        log.debug("remarks:{}",remarks);
//        log.debug("introspectedTable.:{}",introspectedTable.getColumn("id").getActualColumnName());
//        log.debug("introspectedColumn.getRemarks:{}",introspectedColumn.getRemarks());
//        log.debug("introspectedColumn.getContext:{}",introspectedColumn.getContext());
        log.info("introspectedColumn.getActualColumnName:{}", introspectedColumn.getActualColumnName());
//        log.debug("introspectedColumn.getDefaultValue:{}",introspectedColumn.getDefaultValue());
//        log.debug("introspectedColumn.getFullyQualifiedJavaType:{}",introspectedColumn.getFullyQualifiedJavaType());
//        log.debug("introspectedColumn.getIntrospectedTable:{}",introspectedColumn.getIntrospectedTable());
//        log.debug("introspectedColumn.getJavaProperty:{}",introspectedColumn.getJavaProperty());
//        log.debug("introspectedColumn.getProperties:{}",introspectedColumn.getProperties());
//        log.debug("introspectedColumn.getTypeHandler:{}",introspectedColumn.getTypeHandler());
        //根据参数和备注信息判断是否添加备注信息
        if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
//            addFieldJavaDoc(field, remarks);
            //数据库中特殊字符需要转义
            if (remarks.contains("\"")) {
                remarks = remarks.replace("\"", "'");
            }
            //给model的字段添加swagger注解
            field.addJavaDocLine("@ApiModelProperty(value = \"" + remarks + "\")");
        }
        String actualColumnName = introspectedColumn.getActualColumnName();
        log.info("field:", actualColumnName);
        if ("id" == introspectedColumn.getActualColumnName() || "id".equals(introspectedColumn.getActualColumnName())) {
            field.addJavaDocLine("@Id");
            field.addJavaDocLine("@GeneratedValue(generator = \"JDBC\")");
        }

//        IntrospectedColumn tableColumn = introspectedTable.getColumn("id");
//        if (tableColumn.getActualColumnName().equals("id")) {
//            field.addJavaDocLine("@Id");
//            field.addJavaDocLine("@GeneratedValue(generator = \"JDBC\")");
//        }
    }

    /**
     * 给model的字段添加注释
     */
    private void addFieldJavaDoc(Field field, String remarks) {
        //文档注释开始
        field.addJavaDocLine("/**");
        //获取数据库字段的备注信息
        String[] remarkLines = remarks.split(System.getProperty("line.separator"));
        for (String remarkLine : remarkLines) {
            field.addJavaDocLine(" * " + remarkLine);
        }
        field.addJavaDocLine(" */");
    }

    @Override
    protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
        javaElement.addJavaDocLine(" *");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        if (markAsDoNotDelete) {
            sb.append(" do_not_delete_during_merge");
        }
        String s = getDateString();
        if (s != null) {
            sb.append(' ');
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        super.addJavaFileComment(compilationUnit);
        //只在model中添加swagger注解类的导入
        if (!compilationUnit.isJavaInterface() && !compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)) {
            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_GENERATEDVALUE));
            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_ID));
            compilationUnit.addImportedType(new FullyQualifiedJavaType("cn.sell.comm.model.po.BasePO"));
        }
    }

    /**
     * 为模型类添加注释
     */
//    @Override
    public void addModelClassComment(TopLevelClass arg0, IntrospectedTable arg1) {

    }


    /**
     * 为类添加注释
     */
    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        if (addRemarkComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        innerClass.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(" * ");
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
        sb.setLength(0);
        sb.append(" * @author ");
        sb.append(" Limi");
        sb.append(" ");
        innerClass.addJavaDocLine(" */");
    }
}
